package com.cskaoyan.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.cskaoyan.mall.commons.exception.ValidateException;
import com.cskaoyan.mall.commons.util.jwt.JwtTokenUtils;
import com.cskaoyan.user.constants.UserRetCode;
import com.cskaoyan.user.converter.UserConverterMapper;
import com.cskaoyan.user.dal.entitys.Member;
import com.cskaoyan.user.dal.persistence.MemberMapper;
import com.cskaoyan.user.dto.UserLoginResponse;
import com.cskaoyan.user.form.UserLoginRequest;
import com.cskaoyan.user.service.ILoginService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author:ZhouXin
 * @Date:2022/10/25 18:54
 * @Description:
 **/
@Service
@Slf4j
public class ILoginServiceImpl implements ILoginService {
    @Autowired
    MemberMapper memberMapper;

    @Autowired
    UserConverterMapper userConverterMapper;

    @Override
    public UserLoginResponse login(UserLoginRequest request) {
        //验证用户名和密码
        Example example = new Example(Member.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("username",request.getUserName());
        List<Member> memberList = memberMapper.selectByExample(example);
        //判断
        if (CollectionUtils.isEmpty(memberList)){
            throw new ValidateException(UserRetCode.USERORPASSWORD_ERRROR.getCode(),UserRetCode.USERORPASSWORD_ERRROR.getMessage());
        }
        //不为空，对密码做判断，因为注册时候，密码采用了加密，所以先进行加密，加密之后和数据库中的匹配
        Member member = memberList.get(0);
        String password = request.getUserPwd();
        String md5Password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!md5Password.equals(member.getPassword())){
            throw new ValidateException(UserRetCode.USERORPASSWORD_ERRROR.getCode(),UserRetCode.USERORPASSWORD_ERRROR.getMessage());
        }
        //判断用户是否激活
        String isVerified = member.getIsVerified();
        if (!"Y".equals(isVerified)){
            throw new ValidateException(UserRetCode.USER_ISVERFIED_ERROR.getCode(),UserRetCode.USER_ISVERFIED_ERROR.getMessage());
        }

        //打印日志
        log.info("用户登录成功，登录参数request:{}", JSON.toJSON(request));

        //产生token字符串

        Map<String,Object> map=new HashMap<>();
        map.put("uid",member.getId());
        map.put("username",member.getUsername());
        String jsonStr = JSON.toJSONString(map);
        String token = JwtTokenUtils.builder().msg(jsonStr).build().creatJwtToken();
        System.out.println(token);

        //Member转化为响应体对象
        UserLoginResponse response = userConverterMapper.converter(member);

        //将t生成的token赋值给响应体对象
        response.setToken(token);
        return response;
    }
}
